<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Author: Jorge Torres
 * Description: Login controller class
 */
class Users extends My_Controller{
     
    function __construct(){
        parent::__construct();
        ///$this->check_isvalidated();
		$this->load->model('users_model');
		//$this->load->model('counting_model');
    }    
/*
 * Tinh nang quan ly ca nhan
 * */      
    public function index($msg = NULL){
        
    }
	public function verifylogin(){
		// Load the model
       // $this->load->model('users_model');
        // Validate the user can login
        $result = $this->users_model->validate();
        // Now we verify the result
        if(! $result){
            // If user did not validate, then show them login page again
			$msg = '<font color=red>Invalid username and/or password.</font><br />';
            $this->index($msg);
			//redirect('adminvtv4');
        }else{
            // If user did validate, 
            // Send them to members area
            redirect('home');
        }       	
	}
	 public function do_logout(){
        $this->session->sess_destroy();
        $this->index();
    }
 //// view sidebar   
    private function viewSidebar(){
    	$this->load->model('users_model');
    	$this->load->model('counting_model');
    	$user_id = $this->session->userdata('user_id');
    	$level = $this->session->userdata('level');
    	$user_name = $this->session->userdata('user_name');
    	$real_name = $this->users_model->get_real_name($user_name);
    	$avatar = $this->users_model->get_ava($user_id);
    	
    	$counting_articles = $this->counting_model->counting_articles_of_user($user_id);
    	$counting_videos = $this->counting_model->counting_videos_of_user($user_id);
    	$counting_articles_home = $this->counting_model->counting_articles_home_of_user($user_id);
    	$counting_videos_home = $this->counting_model->counting_videos_home_of_user($user_id);
    	
    	$data = array(
    				'user_id' => $user_id,
    				'level'   => $level,
    				'user_name' => $user_name,
    				'real_name' => $real_name,
    				'avatar'  => $avatar,
    				'count_article' => $counting_articles,
    				'count_video' => $counting_videos,
    				'count_article_home' => $counting_articles_home,
    				'count_video_home' => $counting_videos_home
    			);    	
    	$this->load->view('templates/sidebar',$data);
    }
///////
//////////// view doi ava
	public function viewChangeAva(){
		/// counting
		//$data['onlined'] = $this->onlinelib->countOnline();
		//$data['onlining'] = $this->onlinelib->countOnlining();
		$data['numBTV'] = $this->counting_model->numBTV();
		$data['numTP'] = $this->counting_model->numTP();
		$data['numTB'] = $this->counting_model->numTB();
		$data['mostArticle'] = $this->counting_model->articlesViewMost();
		$data['numArticles'] = $this->counting_model->numArticles();
		$data['numReviewArticles'] = $this->counting_model->numReviewArticles();
		
		$user_id = $this->session->userdata('user_id');
		$ava = $this->users_model->get_ava($user_id);
		if($ava)
			$data['avatar'] = $ava;
		else 
			$data['avatar'] = "";
				
		$this->load->view('templates/header');
		$this->viewSidebar();
		$menu['menu'] = 'user';
		$this->load->view('templates/menutop',$menu);
		$this->load->view('user/change_ava_view',$data);
		$this->load->view('templates/footer');
	}  
///////////	
	//Upload image ava dai dien
	private function uploadImages($userfile, $user_id){
	
		$config['upload_path'] = './avas/';
		$config['allowed_types'] = 'gif|jpg|png';
		$config['file_name'] = 'ava_'.$user_id;
		$config['overwrite'] = true;
		$config['max_size']	= '100';
		$config['max_width']  = '1024';
		$config['max_height']  = '768';
	
		$this->load->library('upload', $config);
		
		if(!$this->upload->do_upload($userfile))
		{
			//return $this->upload->display_errors();
			
			?>
					   <script type="text/javascript">		
					   alert('Định dạng ảnh không đúng! Kiểm tra lại dung lượng và kích thước ảnh');					   
						</script>
			<?php	
			return false;					
		} 
		$upload_data = $this->upload->data($userfile);
		
		//print_r($upload_data);
		$ava_img = $upload_data['file_name'];
		return $ava_img;
	}
//////
///////// doi anh dai dien
	public function change_ava(){
		$user_id = $this->session->userdata('user_id');// id user
		$image_thumnail = $this->uploadImages('userfile',$user_id);						// duong dan anh ava				
		if($image_thumnail){
										
			$result = $this->users_model->update_ava($image_thumnail,$user_id);
			if($result){
				$url = base_url()."home";
				echo "<script>alert('Bạn đã đổi ảnh đại diện');	window.location='".$url."'; </script>";
			}
			else echo "model update user error";
		}
	}	
///////
//////////// view doi pass	  
	public function viewChangePassword(){
		/// counting
		//$data['onlined'] = $this->onlinelib->countOnline();
		//$data['onlining'] = $this->onlinelib->countOnlining();
		$data['numBTV'] = $this->counting_model->numBTV();
		$data['numTP'] = $this->counting_model->numTP();
		$data['numTB'] = $this->counting_model->numTB();
		$data['mostArticle'] = $this->counting_model->articlesViewMost();
		$data['numArticles'] = $this->counting_model->numArticles();
		$data['numReviewArticles'] = $this->counting_model->numReviewArticles();
		
    	$this->load->view('templates/header');
		$this->viewSidebar();
		$menu['menu'] = 'user';
		$this->load->view('templates/menutop',$menu);
		$this->load->view('user/changepasswordView',$data);
		$this->load->view('templates/footer');
    }
/////////////
//////////////// doi ten that
	public function view_change_real_name(){
		/// counting
		//$data['onlined'] = $this->onlinelib->countOnline();
		//$data['onlining'] = $this->onlinelib->countOnlining();
		$data['numBTV'] = $this->counting_model->numBTV();
		$data['numTP'] = $this->counting_model->numTP();
		$data['numTB'] = $this->counting_model->numTB();
		$data['mostArticle'] = $this->counting_model->articlesViewMost();
		$data['numArticles'] = $this->counting_model->numArticles();
		$data['numReviewArticles'] = $this->counting_model->numReviewArticles();
		
		$user_name = $this->session->userdata('user_name');		
		$real_name = $this->users_model->get_real_name($user_name);
		if(!$real_name) 
			$data['name'] = array('0'=>'', '1'=>'', '2'=>'');
		else
			$data['name'] = explode("_!@", $real_name);		
		$this->load->view('templates/header');
		$this->viewSidebar();
		$menu['menu'] = 'user';
		$this->load->view('templates/menutop',$menu);
		$this->load->view('user/change_real_name_view',$data);
		$this->load->view('templates/footer');
	}
	public function change_real_name(){
		$ho_name = $this->security->xss_clean($this->input->post('ho_name'));
		$dem_name = $this->security->xss_clean($this->input->post('dem_name'));
		$real_name = $this->security->xss_clean($this->input->post('real_name'));
		$name = $ho_name."_!@".$dem_name."_!@".$real_name;						// ten that
		
		$user_id = $this->session->userdata('user_id');							// id user
		$result = $this->users_model->update_real_name($name,$user_id);
		if($result){
			$url = base_url()."/home";
			echo "<script>alert('Bạn đã đổi tên hiển thị');	window.location='".$url."'; </script>";
		}
		else echo "model update user error";
	}
    public function changepassword(){
	    $this->load->library('form_validation');
	    $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
	    //dieu kien form
	    $this->form_validation->set_rules('password_old', 'Mật khẩu cũ', 'xss_clean|required|min_length[5]|callback_password_check|md5');
		$this->form_validation->set_rules('password_new', 'Mật khẩu', 'xss_clean|required|min_length[5]|matches[re_password_new]|md5');
		$this->form_validation->set_rules('re_password_new', 'Mật khẩu', 'xss_clean|required|min_length[5]|md5');				
		//
    	if ($this->form_validation->run() == FALSE){
    		$this->viewChangePassword();
    	}       	
    	else {        		
    		$password = $this->input->post('password_new');     		
    		$user_id = $this->session->userdata('user_id');
    		$result = $this->users_model->update_password($password,$user_id);
			if($result){
	    		$url = base_url()."/home";
	    		echo "<script>alert('Bạn đã đổi mật khẩu');	window.location='".$url."'; </script>";
			} 
			else echo "model update user error";  		
    	}              
    }
////////////////     kiem tra password
/////////////////////    
    public function password_check($password){
    	$user_id = $this->session->userdata('user_id');
    	$result = $this->users_model->password_check($password,$user_id);
    	
		if (!$result)
		{
			$this->form_validation->set_message('password_check', '%s không đúng');
			return FALSE;
		}
		else
		{			
			return TRUE;
		}
    }

/*
 * Tinh nang quan ly chung
 * */    
    public function viewUser($level){
    	switch ($level){
    		case 1: $this->viewTBUser();
    		break;
    		case 21: $this->viewTBUser();
    		break;
    		case 2: $this->viewTPUser();
    		break;
    		case 3: $this->viewBTVUser();
    		break;
    		case 32: $this->viewTPUser();
    		break;
    	}    	
    }
 ///////////////// view truong ban user
	public function viewTBUser(){
		$data['tb'] = $this->users_model->viewTBUser();		
    	$this->load->view('templates/header');
		$this->viewSidebar();
		$menu['menu'] = 'user';
		$this->load->view('templates/menutop',$menu);
		$this->load->view('user/tb_users_view',$data);
		$this->load->view('templates/footer');
    }
 ///////////////// thong ke tin /video truong ban user
    public function viewTKTBUser(){
    	date_default_timezone_set('UTC');
    	//default
    	$data['fromdate'] = date("Y-m")."-01";			//ngay dau thang
    	$data['todate'] = date("Y-m-d H:i:s");			//ngay hien tai
    	//neu co post
    	if($this->input->post('from_date')) 
    		$data['fromdate'] = $this->input->post('from_date');
    	if($this->input->post('to_date'))
    		$data['todate'] = $this->input->post('to_date');
    	
    	$data['tb'] = $this->users_model->viewTBUser();
    	$this->load->view('templates/header');
    	$this->viewSidebar();
    	$menu['menu'] = 'user';
		$this->load->view('templates/menutop',$menu);
    	$this->load->view('user/tktb_users_view',$data);
    	$this->load->view('templates/footer');
    }    
 ///////////////// view truong phong user
	public function viewTPUser(){
		$data['tp'] = $this->users_model->viewTPUser();
    	$this->load->view('templates/header');
		$this->viewSidebar();
		$menu['menu'] = 'user';
		$this->load->view('templates/menutop',$menu);
		$this->load->view('user/tp_users_view',$data);
		$this->load->view('templates/footer');
    }
 ///////////////// thong ke tin /video truong phong user
    public function viewTKTPUser(){
    	date_default_timezone_set('UTC');
    	//default
    	$data['fromdate'] = date("Y-m")."-01";			//ngay dau thang
    	$data['todate'] = date("Y-m-d H:i:s");			//ngay hien tai
    	//neu co post
    	if($this->input->post('from_date'))
    		$data['fromdate'] = $this->input->post('from_date');
    	if($this->input->post('to_date'))
    		$data['todate'] = $this->input->post('to_date');
    	
    	$data['tp'] = $this->users_model->viewTPUser();
    	$this->load->view('templates/header');
    	$this->viewSidebar();
    	$menu['menu'] = 'user';
		$this->load->view('templates/menutop',$menu);
    	$this->load->view('user/tktp_users_view',$data);
    	$this->load->view('templates/footer');
    }
 ///////////////// view bien tap vien user
	public function viewBTVUser(){
		$data['btv'] = $this->users_model->viewBTVUser();		
    	$this->load->view('templates/header');
		$this->viewSidebar();
		$menu['menu'] = 'user';
		$this->load->view('templates/menutop',$menu);
		$this->load->view('user/btv_users_view',$data);
		$this->load->view('templates/footer');
    }
 ///////////////// thong ke tin /video bien tap vien user
    public function viewTKBTVUser(){
    	date_default_timezone_set('UTC');
    	//default
    	$data['fromdate'] = date("Y-m")."-01";			//ngay dau thang
    	$data['todate'] = date("Y-m-d H:i:s");			//ngay hien tai
    	//neu co post
    	if($this->input->post('from_date'))
    		$data['fromdate'] = $this->input->post('from_date');
    	if($this->input->post('to_date'))
    		$data['todate'] = $this->input->post('to_date');
    	
    	$data['btv'] = $this->users_model->viewBTVUser();
    	$this->load->view('templates/header');
    	$this->viewSidebar();
    	$menu['menu'] = 'user';
		$this->load->view('templates/menutop',$menu);
    	$this->load->view('user/tkbtv_users_view',$data);
    	$this->load->view('templates/footer');
    }
/////////////////	view edit user    
	public function viewEditUser($user_id){	
		$level_user = $this->session->userdata('level');	
		$data['EditUser'] = $this->users_model->viewEditUser($user_id);
    	$this->load->view('templates/header');
		$this->viewSidebar();
		$menu['menu'] = 'user';
		$this->load->view('templates/menutop',$menu);
		
		$error = "<div class='main_container container_16 clearfix'>";
		$error .= "Không có quyền sửa";
		$error .= "</div>";
		
		switch($level_user)
		{
			case 3:				//BTV
				echo $error;
				break;
			case 32:			//TP uy quyen
				echo $error;
				break;	
			case 2:				//TP
				if($data['EditUser']->LEVEL != 3 && $data['EditUser']->LEVEL != 32)
					echo $error;
				else 
					$this->load->view('user/edit_user_view',$data);
				break;
			case 21:			//TB uy quyen
				if($data['EditUser']->LEVEL == 1 || $data['EditUser']->LEVEL == 21)
					echo $error;
				else 
					$this->load->view('user/edit_user_view',$data);
				break;
			case 	1:			//TB
				$this->load->view('user/edit_user_view',$data);				
				break;
			case 4:				//admin
				$this->load->view('user/edit_user_view',$data);
				break;
			default:
				echo $error;
				break;				
		}		 			
		//$this->load->view('user/edit_user_view',$data);
		$this->load->view('templates/footer');
    }
/////////////////	view create user
    public function viewCreateUser(){
		/// counting
		//$data['onlined'] = $this->onlinelib->countOnline();
		//$data['onlining'] = $this->onlinelib->countOnlining();
		$data['numBTV'] = $this->counting_model->numBTV();
		$data['numTP'] = $this->counting_model->numTP();
		$data['mostArticle'] = $this->counting_model->articlesViewMost();
		$data['numArticles'] = $this->counting_model->numArticles();
		$data['numReviewArticles'] = $this->counting_model->numReviewArticles();
		
    	$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
    	$this->load->view('templates/header');
		$this->viewSidebar();
		$menu['menu'] = 'user';
		$this->load->view('templates/menutop',$menu);
		$this->load->view('user/create_user_view',$data);
		$this->load->view('templates/footer');
    } 
/////////////////	control create user
    public function createUser(){
	    $this->load->library('form_validation');
	    //dieu kien form
	    $this->form_validation->set_rules('username', 'Tên đăng nhập', 'xss_clean|required|min_length[5]|callback_username_check');
		$this->form_validation->set_rules('password', 'Mật khẩu', 'xss_clean|required|min_length[5]|matches[re_password]|md5');
		$this->form_validation->set_rules('re_password', 'Mật khẩu', 'xss_clean|required|min_length[5]');				
		//
    	if ($this->form_validation->run() == FALSE){
    		$this->viewCreateUser();
    	}       	
    	else { 
    		$username = $this->input->post('username');
    		$password = $this->input->post('password'); 
    		date_default_timezone_set('UTC');
			$datetime = date("Y-m-d H:i:s");
    		$status = $this->input->post('status_user');
    		$level = $this->input->post('level');	
    		$result = $this->users_model->createUser($username,$password,$datetime,$status,$level);
			if($result){
	    		$url = base_url()."users/viewUser/".$level;
	    		echo "<script>alert('Thêm mới thành công');	window.location='".$url."'; </script>";
			} 
			else echo "model insert user error"; 		
    	}
    }
////////////////// kiem tra user dang nhap
	public function username_check($username){		
		$result = $this->users_model->username_check($username);
		if ($result)
		{
			$this->form_validation->set_message('username_check', '%s đã tồn tại');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
/////////////////	control edit user
    public function editUser($id_user){
	    $this->load->library('form_validation');
	    //dieu kien form
	    if($this->input->post('password') == ""){	    
			$this->form_validation->set_rules('password', 'Mật khẩu', 'xss_clean|min_length[5]|matches[re_password]|md5');
			$this->form_validation->set_rules('re_password', 'Mật khẩu', 'xss_clean|min_length[5]');
	    }				
		//
    	if ($this->form_validation->run() == FALSE){
    		$this->viewEditUser($user_id);
    	}       	
    	else {     		
    		$password = $this->input->post('password');     		
    		$status = $this->input->post('status_user');
    		$level = $this->input->post('level');

    		$result = $this->users_model->editUser($password,$status,$level,$id_user);
			if($result){
	    		$url = base_url()."users/viewUser/".$level;
	    		echo "<script>alert('Cập nhật thành công');	window.location='".$url."'; </script>";
			} 
			else echo "model update user error";   		
    	}
    } 
/////// control del user   
	public function delUser($id_user,$level){
		$result = $this->users_model->delUser($id_user);
		if($result){
    		$url = base_url()."users/viewUser/".$level;
    		echo "<script>alert('Xóa thành công');	window.location='".$url."'; </script>";
		} 
		else echo "model del user error";
	}
}
?>
